from sentry import TaskSentry
from db_function import DataBaseFunction
from util import logger
from datetime import datetime, timezone
import random
class AnalogSendData:


    def __init__(self, devaddr_list) -> None:

        self.devaddr_list = devaddr_list

        self.run()

    @staticmethod
    def parse_command_to_ascII(command: bytearray) -> str: # 命令解释成ascII命令格式
        '''
        >>> parse_command_to_ascII(bytearray([0x16, 0x01, 0x00, 0x00, 0x00, 0x01]))
        >>> 313630313030303030303031
        '''

        res = ""

        for i in command:

            v = hex(i).replace("0x", "")

            val = v if len(v) == 2 else "0"+ v

            for ii in val:

                res += str(hex(ord(ii))).replace("0x", '')

        return res


    def get_analog_data_by_sensor_type(self, devaddr, sensor_type):

        # 获取当前时间
        current_time = datetime.now(timezone.utc)

        # 将时间格式化为指定的格式
        formatted_time = current_time.strftime("%Y-%m-%dT%H:%M:%SZ")

        if '压力' in sensor_type:

            values = ["05 87 09 00 13 012c 7dfe", "05 87 09 00 13 0126 fdf9", "05 87 09 00 13 0122 fc3a"]

            value = random.choice(values)

            data = {
                'codr': '4/5', 
                'data': '303538373039303031333030316566646262', 
                'datetime': formatted_time, 
                'datr': 'SF12BW125', 
                'devaddr': devaddr, 
                'fcnt': 14966, 
                'freq': 471.3, 
                'lsnr': -18.8, 
                'port': 12, 
                'rssi': -71, 
                'text': value.replace(' ', '') # 压力3pa
            }

        elif '倾角' in sensor_type:

            data = {
                'codr': '4/5', 
                'data': '30353837304230303045303031323030314234463239', 
                'datetime': formatted_time, 
                'datr': 'SF12BW125', 
                'devaddr': devaddr, 
                'fcnt': 14966, 
                'freq': 471.3, 
                'lsnr': -18.8, 
                'port': 12, 
                'rssi': -71, 
                'text': '05870B000E0012001B4F29'
            }

        else:

            data = {}


        return {"type": "sensorInfo", "data": data}



    def send_data(self, devaddr):

        with DataBaseFunction() as db:

            sensor_info = db.get_sensors_info_by_devaddr(devaddr=devaddr)

            if not sensor_info: # 无效的传感器地址

                logger.info(f"无效的传感器地址：{devaddr}")

                return 
            
            sensor_type = sensor_info.get('sensor_type')

            data = self.get_analog_data_by_sensor_type(devaddr, sensor_type=sensor_type)
            
            TaskSentry.mqtt_send_data_to_data_center(data=data)

            logger.info(f'{devaddr}:发送模拟数据：')

            logger.info(data)

            logger.info(' ')

    def run(self):

        for devaddr in self.devaddr_list:

            self.send_data(devaddr=devaddr)
            

            

if __name__ == "__main__":

    # 9FF92F87 9CDBF976 91798B12 对应 ABC

    devaddr_list = ["9FF92F87" ,"9CDBF976" ,"91798B12"]

    asd = AnalogSendData(devaddr_list)

    # b = bytearray([0x05, 0x87, 0x09, 0x00, 0x13, 0x00, 0x1e, 0x83, 0xda])
    # b = bytearray([0x05, 0x87, 0x09, 0x00, 0x13, 0x00, 0x1e, 0xfd, 0xbb])
    # print(asd.parse_command_to_ascII(b))


        
